<?php

namespace Yyz\YiYunzhang\Request;

/**
 * Class: RequestGateway
 * @describe:
 * @author: MagicConch17
 * @email: higanbana98@hotmail.com
 * @date: 2020/10/30 11:35
 * @package YiYunzhang\Request
 */
class RequestGateway
{
    private $debug = false;

    /**
     * @param bool $debug
     */
    public function setDebug(bool $debug)
    {
        $this->debug = $debug;
    }

    /**
     * Notes: 核心请求方法
     * @param $url
     * @param $header
     * @param string $method
     * @param mixed $data
     * @param false $ssl
     * @param callable|null $function
     * @return bool|string
     * @date: 2020/10/30 14:42
     * @author: MagicConch17
     */
    public function Quest($url, $header, $method = 'POST', $data = '', $ssl = true, callable $function = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);

        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
        } elseif ($method != 'GET') {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        }

        if (!empty($data)) curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);

        if (count($header) > 0) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);

        if ($ssl) {
            //规避SSL验证
			  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            // curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 2);
            //跳过HOST验证
            // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        }

        $output = curl_exec($curl);

        return $output;

//        if (true) {
//            echo(curl_getinfo($curl,CURLINFO_HEADER_OUT));
//        }
//        curl_close($curl);
//
//        if ($function !== null || is_callable($function)) {
//            return $function($output);
//        } else {
//            return json_decode($output, true);
//        }
    }
}
